/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.openjpa.jdbc.meta.MappingTool;
import org.apache.openjpa.jdbc.meta.ReverseMappingTool;
import org.junit.Test;

/**
 *
 * @author changshu.li
 */
public class JpaEntityHelp {

  public static File src = new File(JpaEntityHelp.class.getResource("/").getFile() + "../../src/main/java/");

  //@Test
  public void db2entity() throws IOException, SQLException {
    String f = src.getAbsolutePath();
    ReverseMappingTool.main(new String[]{"-pkg", "cn.xy.coin.eth.domain", "-d", f, "-annotations", "true", "-nullableAsObject", "true"});
  }

  //@Test
  public void entity2db() throws IOException, SQLException {
    MappingTool.main(new String[]{"com.market.server.domain.Account"});
  }

  //@Test
  public void entity2repository() throws IOException {
    List<String> list = listEntity();
    String tempname = "AccountRepository.java";
    String tempmsg = "Account";
    String repos = src.getPath() + ".com.market.server.repository".replaceAll("\\.", File.separator + File.separator);
    String tmp = repos + File.separator + tempname;
    String cnt = FileUtils.readFileToString(new File(tmp));
    for (String name : list) {
      String ncmt = cnt.replaceAll(tempmsg, name);
      String fname = tempname.replace(tempmsg, name);
      String nname = repos + File.separator + fname;
      File nfile = new File(nname);
      if(nfile.exists()){
      }else{
        nfile.createNewFile();
      }
      FileUtils.write(nfile, ncmt);
    }
  }

  public List<String> listEntity() {
    String entitypath = src.getPath() + ".com.market.server.domain".replaceAll("\\.", File.separator + File.separator);
    File file = new File(entitypath);
    File[] fs = file.listFiles();
    List<String> list = new ArrayList();
    for (File f : fs) {
      if (f.getName().endsWith(".java")) {
        list.add(f.getName().split("\\.")[0]);
      }
    }
    return list;
  }

}